﻿import _ from 'lodash'
import config from '@/config'
const NodeRSA = require('node-rsa')
var md5 = require('js-md5');
import actions_c from '@/store/actions.js'
const actions = actions_c()
const moment = require('moment')
import {mixValue, withUnit, dict} from '@/const'
let outputPath = config.path.output
let parsePath = require('parse-filepath')
const DICT = dict
const codehash = window.codehash
import base64 from 'base-64'

var __dirpath;
if(globalThis===window){//浏览器环境

}else{//nodejs 环境
	__dirpath = __path.dirname(node_process.execPath).replace(/\\/g,'/')
	window.__dirpath = __dirpath = process.env.NODE_ENV == 'production' ? __dirpath : '.'
}

console.log("__dirpath",  __dirpath, process.env.NODE_ENV)

export function render_list(list,fn){
    var vnode=[];
    try{
        list.forEach((item,index)=>{
            vnode.push(fn(item,index));
        });
    }catch(e){
    }
    return vnode;
}
export function render_obj(obj,fn){
	var piece=[];
	for(let prop in obj){
		piece.push(fn(prop,obj[prop]))
	}
	return piece;
}
export function getNodeByPath(nodeTree,path){
	var tem=nodeTree
	for(let i in path){
		if(i==0){
			tem=tem[i]
		}else{
			tem=tem.children[path[i]]
		}
	}
	return path.length>0 && JSON.stringify(nodeTree)!='[]' ? tem : null
}
export function sizeToNum(sizeStr){
	var sizeStr= sizeStr.replace(/px$|pt$|em$|rem$/,'');
	return parseFloat(sizeStr);
}
export function revisePosition(selector, boundary, callback){
	var bd = {
		x:$(boundary).width(),
		y:$(boundary).height()
	}
	$(selector).each(function(){
		var revise = {
			x: bd.x - $(this).css('left').replace('px',''),
			y: bd.x - $(this).css('top').replace('px','')
		}
		callback(this, revise)
	})
}
/*
*@params(
	path //父级path
)
*/
export function hasSelector(path, nodeTree){
	var test = false
	for(let i=path.length;i>path.length-3;i--){
		let node = getNodeByPath(nodeTree, _.take(path, i))
		if(node.class.length != 0){
			test = test || true
			break
		}
	}
	return test
}
export function getSelector(path, nodeTree){
	var selector = []
	for(let i=path.length - 3; i>path.length; i++){
		let node = getNodeByPath(nodeTree, _.take(path, i))
		if(node.class.length != 0){
			selector.push(node.class[0])
		}
	}
	return selector
}
export function isTagNoEnd(tagName){
	return /^br$|^hr$|^img$|^option$|^meta$|^link$/.test(tagName)
}
//遍历nodeTree
export function eachNode(nodes, fn){
	nodes.forEach((item)=>{
		fn(item)
	})
}

export function jsonToLess(str){
	str = str.replace(/:{/g,"{")
	str = str.replace(/"/g,"")
	str = str.replace(/,/g,";")
	return str.substr(1,str.length-2)
}
// return moment
export function latestTime(){
	var latestTime = moment.utc()
	let dir_s = [os.homedir(), os.tmpdir()]
	dir_s.forEach((dir)=>{
		let nameList = fs.readdirSync(dir);
		nameList.forEach((path,index)=>{
			try{
				let stats = fs.statSync(`${dir}/${path}`);
				let time = moment.utc(stats.mtimeMs)
				latestTime = moment.max(time, latestTime)
			}catch(e){
			}
		})
	})
	return latestTime
}
export async function checkLicenseTime(licenseInfo){
	let nowTime = latestTime()
	let leftDays = moment.utc(licenseInfo.eTime).diff(nowTime,'days')
	leftDays = leftDays<0 ? 0 : leftDays*1
	if(moment.utc(licenseInfo.eTime).isBefore(nowTime)){
		setTimeout(()=>{
			store.dispatch(actions.updateLicense({
				status:2,
				msg: _.get(dict.licenseStatus,'2',''),
				leftDays,
				trial: licenseInfo.trial
			}))
		},0)
	}else{
		setTimeout(()=>{
			store.dispatch(actions.updateLicense({
				status:0,
				msg: _.get(dict.licenseStatus,'0',''),
				leftDays,
				trial: licenseInfo.trial
			}))
		},0)
	}
}
export function isNumber(_val){
	try{
		if(_.trim(_val) == ''){
			return false
		}else{
			return !isNaN(_val * 1)
		}
	}catch(e){
		return false
	}
}
export function addUnit(_node){
	let reg = new RegExp(`${mixValue.join("|")}`)
	Object.keys(_.get(_node,'styles',[])).forEach((prop)=>{
		let _val = _node.styles[prop]
		if(`,${withUnit.join(',')},`.indexOf(`,${prop},`)==-1)return
		if(reg.test(prop)){//is mix value
			if(isNumber(_val)){ // number
				_node.styles[prop] = `${_node.styles[prop]}${config.unit}`
			}else{
				let parts = (_node.styles[prop]).split(" ")
				for(let i in parts){
					let num = _.toNumber(parts[i])
					if(isNumber(_val)){
						parts[i] = `${parts[i]}${config.unit}`
					}
				}
				_node.styles[prop] = parts.join(" ")
			}
		}else{
			if(isNumber(_val)){
				_node.styles[prop] = `${_node.styles[prop]}${config.unit}`
			}
		}
	})
}
export function ObjectToArray(obj){
	let array = []
	for(let prop in obj){
		array.push({
			key: prop,
			value: obj[prop]
		})
	}
	return array
}
export function ArrayToObject(arr,key='key',value='value'){
	let obj = {}
	for(let i in arr){
		if(!arr[i].key && !arr[i].value){
			continue
		}
		obj[arr[i][key]] = arr[i][value]
	}
	return obj
}
//when add a node need calculation the next path
export function newNodePath(currentPath,currentDom,currentNode,nodeTree){
	Object.assign(currentNode, {children:[]}, currentNode)
	let path = _.clone(currentPath)
	let index = 0
	let _currentPath = currentPath
	if($(currentDom).hasClass('emidraw-paper')){
		_currentPath = []
		index = nodeTree.length
	}else{
		index = currentNode.children.length
	}
	path.push(index)
	return {addToPath:_currentPath, newNodePath: path}
}
export async function mac(){
	let netInf = await  os.networkInterfaces()
	let mac = []
	Object.keys(netInf).forEach((key)=>{
		netInf[key].forEach((item)=>{
			if(item.mac!="00:00:00:00:00:00" && mac.indexOf(item.mac)==-1){
				mac.push(item.mac)
			}
		})
	})
	return mac
}
export function save(){
	var data=store.getState().nodeTree[0].children
	data=JSON.stringify(data)
	if(globalThis===window){
		
	}else{
		fs.writeFile(`${outputPath}/data.json`, data,function(err) {
		});
	}
	
}
export function debounce(fn, delay = 500, immediate = false) {
    let timerid = null 
    let wait = false
    return function(){
        let args = arguments
        if(immediate){
            if(!wait){
                fn(...args)
                wait = true
            } 
            if(timerid) clearTimeout(timerid) 
            timerid = setTimeout(()=>{
                wait = false
            }, delay)
        }else{
            if(timerid) clearTimeout(timerid)
            timerid = setTimeout(()=>{
                fn(...args)
            }, delay)
        }
    }
}
export function getLessStyle (nodes,style={},htmlImages = []){
	if(!_.isArray(nodes)){return;}
	if(nodes.length<1){return;}
	nodes.forEach((item,index)=>{
		let path = _.isArray(item.selector) ? item.selector : [];
		if(_.has(item,'styles') && _.get(item,'attr.class.length',0)!=0){
			for(let prop in item.styles){
				let _path = _.clone(path);
				_path.push(_.kebabCase(prop));
				let  styleValue = item.styles[prop];
				_.set(style, _path, styleValue);
				if(prop.toLowerCase()=='background'){
				}
			}
		}
		if(item.tag=='img'){
			try{
				let pathPre = "file://";
				let src = item.attr.src.replace(pathPre,"");
				let pathObj = parsePath(src);
				let dest = `${outputPath}/${pathObj.basename}`;
				fs.copyFile(src, dest, function(e){
				});
				htmlImages.push({
					from: `${pathPre}${src}`,
					to: pathObj.basename
				});
			}catch(e){
			}
		}
		createLessStyle(_.get(item, 'children'), style, htmlImages);
	});
	return {lessStyle:style,htmlImages};
};